package com.heima.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * app端登录功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        // 1.判断是否为正常登录
        if (StrUtil.isNotBlank(dto.getPhone()) && StrUtil.isNotBlank(dto.getPassword())) {
            // 1.1正常登录，查询用户
            ApUser apUser = this.lambdaQuery()
                                .eq(ApUser::getPhone, dto.getPhone())
                                .one();
            // 1.2判断用户是否存在，不存在直接返回
            if (ObjectUtil.isNull(apUser)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
            // 1.3判断密码是否正确，不正确直接返回
            String password = dto.getPassword();
            String salt = apUser.getSalt();
            password = SecureUtil.md5(password + salt);
            if (ObjectUtil.notEqual(password, apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 1.4生成token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            log.info("登录成功生成token：{}", token);
            // 1.5返回数据
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        }

        // 2.游客登录
        Map<String, Object> map = new HashMap<>();
        String token = AppJwtUtil.getToken(0L);
        log.info("游客登录成功生成token：{}", token);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}
